const koa = require('koa')
const app = new koa()
const session = require('koa-session')
const Router = require('koa-router')
const router = new Router()

app.use(router.routes())
app.use(router.allowedMethods())

app.keys = ['hi koa']

app.use(session(app))

app.use(ctx => {
  ctx.type = 'text/html; charset=utf-8'
  if(ctx.path === '/favicon.ico') return
  let n = ctx.session.views || 0
  ctx.session.views = ++n
  if (ctx.path === '/') {
    ctx.body = n + 'views'
  } else if (ctx.path === '/hi') {
    ctx.body = 'hi koa'
  } else {
    ctx.body = '404'
  }
})

router.get('/test2', (ctx, next) => {
  console.log('test2')
  ctx.body = 'test2'
  next()
}, (ctx, next) => {
  console.log('test4')
  ctx.body += 'test4'
  next()
})
router.get('/test2', (ctx, next) => {
  console.log('test3')
  ctx.body += 'test3'
})
// app.use(async (ctx, next) => {
//   ctx.body = 'hi koa'
//   ctx.type = 'text/html; charset=utf-8'
//   // console.log(next())
//   await next()
//   return 'haha'
// }) 
// app.use(async (ctx, next) => {
//   await new Promise((res) => {
//     setTimeout(() => {
//       ctx.body = ctx.body + '2333'
//       res()
//       // next()
//     }, 0)
//   })
// })
app.listen(2333)
